from django.db import models

from django.contrib.auth.models import User

import re

class Page(models.Model):
    
    path = models.CharField(max_length=200)
    content = models.TextField(blank=True)
    content_type = models.CharField(max_length=10)
    page_title = models.CharField(max_length=150, blank=True, null=True)
    author = models.ForeignKey(User)
    creation_time = models.DateTimeField()
    last_modified = models.DateTimeField()
    categories = models.ManyToManyField('Category', blank=True, null=True, filter_interface=models.HORIZONTAL)
    allow_comments = models.CharField(max_length=10, choices=[('NO', 'NO'), ('YES', 'YES'), ('READ-ONLY', 'READ_ONLY')])
    
    def comments(self):
        return self.comment_set.order_by('creation_time')
    
    def get_absolute_url(self):
        return "/" + self.path + "/"
    
    def __unicode__(self):
        return self.path
    
    class Admin:
        list_display = ('path', 'content_type', 'page_title', 'author', 'creation_time', 'last_modified', 'allow_comments')


class Comment(models.Model):
    
    page = models.ForeignKey(Page)
    comment = models.TextField()
    last_modified = models.DateTimeField()
    creation_time = models.DateTimeField()
    
    author_name = models.CharField(max_length=100, null=True, blank=True)
    author_link = models.CharField(max_length=100, null=True, blank=True)
    author_email = models.EmailField(max_length=100, null=True, blank=True)
    
    author_ipaddress = models.IPAddressField(null=True)
    
    # if author is non-NULL, author_name, author_link and author_email above should be NULL
    author = models.ForeignKey(User, null=True)
    
    def formatted_comment(self):
        comment = re.sub(r"&", "&amp;", self.comment)
        comment = re.sub(r"<", "&lt;", comment)
        return re.sub(r"\r\n", "<br />", comment)
    
    def get_absolute_url(self):
        return "/" + self.page.path + "/" # @@@
    
    class Admin:
        list_display = ('id', 'page', 'author', 'author_name', 'author_link', 'author_email', 'creation_time', 'author_ipaddress')


class Category(models.Model):
    
    term = models.CharField(max_length=50)
    
    def get_absolute_url(self):
        return "/" + self.term + "/"
    
    def __unicode__(self):
        return self.term
    
    class Meta:
        verbose_name_plural = 'categories'
    
    class Admin:
        list_display = ('id', 'term')


class StaticFile(models.Model):
    
    path = models.CharField(max_length=100)
    content_type = models.CharField(max_length=10)
    author = models.ForeignKey(User)
    creation_time = models.DateTimeField()
    last_modified = models.DateTimeField()
    
    class Admin:
        list_display = ('path', 'content_type', 'author', 'creation_time', 'last_modified')
